﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace KeyCount
{
    public partial class MainForm : Form
    {
        #region 变量
        /// <summary>
        /// 钩子类
        /// </summary>
        private KeyboardHookLib _keyboardHook = null;
        /// <summary>
        /// 按键次数
        /// </summary>
        private int KeyNums = 0;
        /// <summary>
        /// 按键速度
        /// </summary>
        private decimal keySpeed = 0;
        /// <summary>
        /// 记录timer控件当前触发次数
        /// </summary>
        private decimal timeCount = 0;
        /// <summary>
        /// 当前一分钟内按键次数
        /// </summary>
        private decimal keysNumsMin = 0;
        /// <summary>
        /// xml文档路径
        /// </summary>
        private static string xmlPathFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "KeyCount.xml";
        /// <summary>
        /// 实例化xml文件操作类
        /// </summary>
        private XmlHelper xmlHelper = new XmlHelper();
        /// <summary>
        /// 按键信息集合
        /// </summary>
        private static IList<Model.KeysInfo> keysInfoList = new List<Model.KeysInfo>();
        #endregion

        #region 事件
        public MainForm()
        {
            InitializeComponent();
            //这个区域不包括任务栏的
            Rectangle ScreenArea = System.Windows.Forms.Screen.GetWorkingArea(this);
            int width1 = ScreenArea.Width; //屏幕宽度 
            int height1 = ScreenArea.Height; //屏幕高度
            this.Location = new System.Drawing.Point(width1 - 525, height1 - 353);  //指定窗体显示在右下角
        }
        /// <summary> 
        /// 客户端键盘捕捉事件. 
        /// </summary> 
        /// <param name="hookStruct">由Hook程序发送的按键信息</param> 
        /// <param name="handle">是否拦截</param> 
        public void OnKeyPress(KeyboardHookLib.HookStruct hookStruct, out bool handle)
        {
            handle = false;
            Keys key = (Keys)hookStruct.vkCode;
            if (hookStruct.flags > 0)     //判断按键是否按下
            {
                KeyNums++;
                keysNumsMin++;
                Model.KeysInfo keysInfoModel = new Model.KeysInfo();
                keysInfoModel.KeyName = key.ToString();
                keysInfoModel.KeyNum = 1;
                keysInfoModel.KeyOnTime = DateTime.Now;
                keysInfoList.Add(keysInfoModel);
                if (keysInfoList != null && keysInfoList.Count > 100)    //为了避免保存的时候工作量太大，数量大于100后自动保存，并清空
                {
                    SaveKeysInfo();
                }
                digitalGauge1.Text = KeyNums.ToString();
            }
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            InstallationHook();
            try
            {
                xmlHelper.XmlPath = xmlPathFile;    //将xml文件路径赋值给xml类中的属性
                if (!File.Exists(xmlPathFile))    //若不存在xml文件则创建一个
                {
                    xmlHelper.CreateXml();
                }
                KeyNums = Convert.ToInt32(xmlHelper.ReadXmlElement("KeysSum"));
                digitalGauge1.Text = KeyNums.ToString();
            }
            catch (Exception ae)
            {
                MessageBox.Show(ae.Message, this.Text);
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!xmlHelper.ExistsXmlElement("KeysSum"))
            {
                xmlHelper.CreateXmlElement("Root", "KeysSum");
                xmlHelper.UpdataXmlElement("KeysSum", KeyNums.ToString());
            }
            else
            {
                xmlHelper.UpdataXmlElement("KeysSum", KeyNums.ToString());
            }
            SaveKeysInfo();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            btnSave_Click(sender, e);
            this.Close();
        }
        private void timerSpeed_Tick(object sender, EventArgs e)
        {
            timeCount++;
            if (timeCount > 0)      //大于零，执行
            {
                if (timeCount == 60)
                {
                    keysNumsMin = 0;
                    timeCount = 1;
                }
                decimal speedS = keysNumsMin / timeCount;
                decimal speedMin = speedS * 60;
                labelComponent1.Text = Math.Round(speedMin, 2).ToString() + "/mi";
                labelComponent2.Text = Math.Round(speedS, 2).ToString() + "/s";
                arcScaleComponent3.Value = Convert.ToInt32(speedS);
                arcScaleComponent1.Value = Convert.ToInt32(speedMin);
            }
        }
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnSave_Click(sender, e);
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnExit_Click(sender, e);
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void 隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }
        #endregion

        #region 方法

        /// <summary>
        /// 存储键盘信息
        /// </summary>
        private void SaveKeysInfo()
        {
            if (keysInfoList != null && keysInfoList.Count > 0)
            {
                string elementName = "";
                foreach (Model.KeysInfo ki in keysInfoList)
                {
                    elementName = ki.KeyName;
                    if (!xmlHelper.ExistsXmlElement(elementName))
                    {
                        xmlHelper.CreateXmlElement("Root", elementName);
                        xmlHelper.UpdataXmlElement(elementName, "1");
                    }
                    else
                    {
                        int num = Convert.ToInt32(xmlHelper.ReadXmlElement(elementName)) + 1;
                        xmlHelper.UpdataXmlElement(elementName, num.ToString());
                    }
                }
                keysInfoList.Clear();
            }
        }

        /// <summary>
        /// 安装键盘钩子
        /// </summary>
        private void InstallationHook()
        {
            try
            {
                //安装勾子 
                _keyboardHook = new KeyboardHookLib();
                _keyboardHook.InstallHook(this.OnKeyPress);
            }
            catch (Exception ex)
            {
                MessageBox.Show("安装钩子失败！\r原因：" + ex);
            }
        }
        /// <summary>
        /// 卸载钩子
        /// </summary>
        private void UninstallHook()
        {
            //取消勾子 
            if (_keyboardHook != null)
            {
                _keyboardHook.UninstallHook();
            }
        }
        #endregion
    }
}
